package com.huawei.frs.demo;

import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.core.http.HttpConfig;
import com.huaweicloud.sdk.core.region.Region;
import com.huaweicloud.sdk.frs.v2.FrsClient;
import com.huaweicloud.sdk.frs.v2.model.CompareFaceByBase64Request;
import com.huaweicloud.sdk.frs.v2.model.CompareFaceByBase64Response;
import com.huaweicloud.sdk.frs.v2.model.FaceCompareBase64Req;
import com.huaweicloud.sdk.frs.v2.region.FrsRegion;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class Demo {

    private static final Logger LOGGER = LoggerFactory.getLogger(Demo.class.getName());

    public static String getImgStr(String imgPath) {
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            int read = in.read(data);
            LOGGER.debug(String.format("data read : %s", read));
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    LOGGER.error(e.getMessage());
                }
            }
        }
        return Base64.encodeBase64String(data);
    }

    public static void main(String[] args) {
        // 替换为真实的AK SK
        String ak = "Qa2**************QdV";
        String sk = "aBD**********************************cRv";

        // 获取resources下的文件路径（使用时，需要替换为真实的文件）
        URL faceFile = Demo.class.getClassLoader().getResource("data/face-demo.jpg");

        // 将图片转为base64
        String imageBase64 = getImgStr(faceFile.getPath());

        // Init Auth Info
        ICredential credential = getCredential(ak, sk);

        // create frsClient
        FrsClient client = getclient(FrsRegion.CN_NORTH_4, credential);

        // 人脸比对Base64方式
        compareFaceByBase64(client, imageBase64, imageBase64);
    }

    /**
     * 获取鉴权
     *
     * @param ak 开通人脸识别服务账号的AK
     * @param sk 开通人脸识别服务账号的SK
     * @return 认证信息
     */
    public static ICredential getCredential(String ak, String sk) {
        return new BasicCredentials().withAk(ak).withSk(sk);
    }

    /**
     * 初始化客户端
     *
     * @param region 开通服务的RegionID
     * @param auth 认证信息
     * @return frs客户端
     */
    public static FrsClient getclient(Region region, ICredential auth) {
        // 跳过SSL认证，可删除
        HttpConfig config = HttpConfig.getDefaultHttpConfig();
        config.withIgnoreSSLVerification(true);
        return FrsClient.newBuilder().withCredential(auth).withRegion(region).withHttpConfig(config).build();
    }

    /**
     * 人脸比对
     *
     * @param client 初始化的frs客户端
     * @param image1Base64 比对的第一张人脸图片的base64编码
     * @param image2Base64 比对的第二张人脸图片的base64编码
     */
    private static void compareFaceByBase64(FrsClient client, String image1Base64, String image2Base64) {
        CompareFaceByBase64Request compareRequest = new CompareFaceByBase64Request();
        FaceCompareBase64Req faceCompareBase64Req = new FaceCompareBase64Req();
        faceCompareBase64Req.withImage1Base64(image1Base64);
        faceCompareBase64Req.withImage2Base64(image2Base64);
        compareRequest.withBody(faceCompareBase64Req);
        try {
            CompareFaceByBase64Response compareResponse = client.compareFaceByBase64(compareRequest);
            System.out.println(compareResponse.toString());
        } catch (ConnectionException e) {
            LOGGER.error(e.toString());
        } catch (RequestTimeoutException e) {
            LOGGER.error(e.toString());
        } catch (ServiceResponseException e) {
            LOGGER.error(e.getErrorMsg());
        }
    }

}